import datetime
import json
import os
import Logger

import xlrd
from xlrd import Book
from xlrd.sheet import Sheet
import Util

from ExcelData import ExcelData, TableData, FieldData, FieldType, EData, LoadConfig, IndexType, Platform, Union
from typing import List, Dict

def exportFile(exportVersion:str, exportTime:datetime):
    # exportTime = datetime.datetime.now()
    # exportVersion = uuid.uuid1()
    log: Logger = Logger.Logger()
    edata = EData()

    # 删除之前生成的.java文件
    filelist = os.listdir(edata.setting.defDirJsonFile)
    for filename in filelist:
        filepath = edata.setting.defDirJsonFile + filename
        if os.path.isfile(filepath):
            if filename.endswith(".json") and not filename == edata.setting.defDefineJsonFile:
                os.remove(filepath)
                print("删除旧文件：" + filepath)

    strIgnore = edata.setting.readerCfgIgnoreColumn.replace("，",",")
    arrIgnore = strIgnore.split(",")
    for i in range(0,len(arrIgnore)):
        arrIgnore[i] = arrIgnore[i].strip().lower()
    for excel in edata.excelDatas.values():
        if not os.path.isfile(excel.filePath):
            log.logError("文件打开错误！ 文件名：" + excel.filePath)
            continue
        workbook: Book = xlrd.open_workbook(excel.filePath)
        # 遍觅每个excel文件
        for table in excel.tables.values():
            # 检查是否已勾选导出
            if not table.isListChecked:
                continue
            for sname in workbook.sheet_names():
                # 遍觅每个sheet
                if table.sheetName == sname:
                    # 正式开始读取数据
                    jsonData = {}
                    sheet: Sheet = workbook.sheet_by_name(sname)
                    jsonRows = []
                    count: int = 0
                    for r in range(table.fieldDataRowIndex, sheet.nrows):
                        # 遍觅每一行数据
                        row = sheet.row(r)
                        jsonField = {}
                        isSkipField = False
                        skipStr: str = row[0].value
                        skipStr = skipStr.strip(" ").lower()
                        # 跳过不导出字段
                        isSkip:bool = False
                        for ignore in arrIgnore:
                            if skipStr == ignore:
                                isSkip = True
                        if isSkip:
                            continue

                        for fData in table.fields:
                            # 根据预分析的field.colunmOrd，知道哪一列是数据列，直接获取不遍觅
                            field: FieldData = fData
                            objValue = row[field.colunmOrd].value
                            strValue: str = str(objValue)
                            if field.canNotEmpty and strValue.strip() == "":
                                # 已经没有数据了，不导出
                                isSkipField = True
                                continue

                            # 整形数据赋值
                            if field.fieldType == FieldType.Integer:
                                if objValue is None or objValue == "":
                                    jsonField[field.fieldKey] = 0
                                else:
                                    value = int(objValue)
                                    jsonField[field.fieldKey] = value

                            # 浮点数据赋值
                            if field.fieldType == FieldType.Float:
                                if objValue is None or objValue == "":
                                    jsonField[field.fieldKey] = 0.0
                                else:
                                    jsonField[field.fieldKey] = objValue
                                    # value = float(objValue)
                                    # jsonField[field.fieldKey] = value

                            # 64位整形与浮点数据赋值（以字符形式）
                            if field.fieldType == FieldType.Long or field.fieldType == FieldType.Double:
                                if objValue is None or objValue == "":
                                    jsonField[field.fieldKey] = "0"
                                else:
                                    jsonField[field.fieldKey] = str(objValue)

                            # 字符串赋值
                            if field.fieldType == FieldType.String:
                                jsonField[field.fieldKey] = str(objValue)

                            # 布尔赋值
                            if field.fieldType == FieldType.Boolean:
                                val = str(objValue).lower().strip()
                                if val == "true" or val == "1" or val == "t":
                                    jsonField[field.fieldKey] = True
                                else:
                                    jsonField[field.fieldKey] = False

                        if not isSkipField:
                            jsonRows.append(jsonField)
                            count += 1
                    # json表头
                    table.lastExecuteTime = datetime.datetime.now()
                    headData: dict = dict()
                    headData["version"] = exportVersion
                    headData["date"] = Util.getDateTimeString(exportTime)
                    headData["count"] = count
                    jsonData["header"] = headData
                    # 表格数据
                    jsonData["data"] = jsonRows
                    jsonStr = json.dumps(jsonData, ensure_ascii=False, indent=2)
                    # print(jsonStr)
                    if jsonStr is not None:
                        filepath = edata.setting.defDirJsonFile + table.jsonName + ".json"
                        f = open(filepath, 'w', encoding='utf8')
                        f.write(jsonStr)
                        f.close()
                        log.logSuccess("导出 [" + table.jsonName + "]" + table.sheetName + " 成功，共导出数据行：" + str(count))

    return True


def exportFileSetting(exportVersion:str, exportTime:datetime):
    log: Logger = Logger.Logger()
    edata: EData = EData()
    headData: dict = dict()
    headData["version"] = exportVersion
    headData["date"] = Util.getDateTimeString(exportTime)
    loadconfigs:[] = []
    for excel in edata.excelDatas.values():
        for table in excel.tables.values():
            for loadCfg in table.loadConfigs:
                cfg:dict = dict()
                keysets = []
                for key in loadCfg.keyFields:
                    keyset = {}
                    keyset["name"] = key.fieldKey
                    # for kf in table.fields:
                    #     if kf.fieldKey == key:
                    # keyset["type"] = kf.fieldType.name
                    keyset["type"] = key.fieldType.name
                    keysets.append(keyset)
                cfg["keys"] = keysets
                cfg["mainKey"] = keysets[0]["name"]
                cfg["mainKeyType"] = keysets[0]["type"]
                cfg["type"] = loadCfg.type.name
                cfg["loadWeight"] = loadCfg.loadWeight
                cfg["loadJson"] = table.jsonName
                cfg["comment"] = table.sheetName
                cfg["className"] = table.getClassname()
                cfg["dataName"] = loadCfg.getDataName(table)
                cfg["dataFullName"] = loadCfg.getDataFullName(table)
                # 导出平台资料
                platforms:[] = []
                for platform in loadCfg.exportPlatforms.values():
                    platforms.append(platform.name)
                cfg["platforms"] = platforms
                # 导出关联字段
                unions:[] = []
                for union in loadCfg.unions:
                    u:dict = dict()
                    u["key"] = union.myKey
                    u["unionTable"] = union.unionTableName
                    u["unionKey"] = union.unionKey
                    unions.append(u)
                cfg["unions"] = unions
                # 导出组别
                cfg["group"] = edata.setting.groupPrefix + loadCfg.group
                # 导出关联字段
                loadRelations:List[str] = []
                for strRelation in loadCfg.loadRelations:
                    frTable:TableData = None
                    for rExcel in edata.excelDatas.values():
                        for rTable in rExcel.tables.values():
                            if rTable.sheetName == strRelation:
                                frTable = rTable
                    if frTable is None:
                        log.logError("严重错误！配置中关联加载中找不到关联表格：" + strRelation)
                        return False
                    loadRelations.append(frTable.jsonName)
                cfg["loadRelations"] = loadRelations
                loadconfigs.append(cfg)

    jsonData = {}
    headData["count"] = len(loadconfigs)
    jsonData["header"] = headData
    jsonData["defines"] = loadconfigs
    jsonStr = json.dumps(jsonData, ensure_ascii=False, indent=2)
    if jsonStr is not None:
        filepath = 'output/' + edata.setting.defDefineJsonFile
        f = open(filepath, 'w', encoding='utf8')
        f.write(jsonStr)
        f.close()
        log.logSuccess("导出定义文件成功，共导出数据行：" + str(len(loadconfigs)))

    return True